<template>
  <div class="h-full w-full">
    <SplitPanel :style="{ 'flex-direction': 'row !important' }" class="dept-page-box">
      <template #left-content >
        <div class="flex justify-between flex-col h-full ">
          <a-input-search
            v-model:value="searchValue"
            style="margin-bottom: 8px"
            placeholder="请输入"
          />
          <Tree
            v-model:expandedKeys="state.expandedKeys"
            auto-expand-parent
            :tree-data="state.orgTree"
            v-if="state.showTree"
            >
            <!-- @select="onTreeSelect" -->
            <template #title="treeItem">
              <span  
              @click="(val) => onTreeSelect([treeItem.id],treeItem)"
              >
                {{ treeItem.title }}
              </span>
              <NDropDown
                :dropItems="dropItems"
                @click="(val) => handleTreeItemClick(val, treeItem,2)"
                class="ml-10px"
              />
            </template>
          </Tree>
        </div>
      </template>
      <template #right-content>
        <DynamicTable show-index :data-request="loadTableData" :columns="columns">
          <!-- <template #toolbar>
            <a-button type="primary" @click="openModal"> <PlusOutlined /> 新增 </a-button>
          </template> -->
        </DynamicTable>
      </template>
    </SplitPanel>
  </div>
</template>

<script setup lang="tsx">
  import { ref, reactive, defineComponent, onMounted, h, watch, unref ,nextTick} from 'vue';
  import { PlusOutlined, EditOutlined, PlusCircleOutlined,DeleteOutlined } from '@ant-design/icons-vue';
  import { Tree, Modal, Alert, message } from 'ant-design-vue';
  import type { FormInstance } from 'ant-design-vue';
  import { 
    baseColumns,
    type DeptListItem,
    type TableColumnItem } from '@/views/organization/departments/columns';
  import {formatFormSortTree,formatExpandFormSortTree} from '@/views/organization/orgs/columns';
  import type { LoadDataParams } from '@/components/core/dynamic-table';
  import type { TreeDataItem } from '@/core/permission/utils';
  import { SplitPanel } from '@/components/basic/split-panel';
  import { useTable } from '@/components/core/dynamic-table';
  import { getOrgList,createOrg, updateOrg,deleteOrg } from '@/api/organization/orgs/orgs';
  import { getDeptsList, createDept, updateDept, deleteDept ,getDepartmentEntityList} from '@/api/organization/depts/depts';
  import { flatTree,formatDept2Tree } from '@/core/permission/utils';
  import {handleTree} from '@/utils/common';
  import { useModal } from '@/hooks/useModal/useModal';
  import DeptDetail from './deptDetail.vue';
  import OrgDetail from '@/views/organization/orgs/orgDetail.vue';
  import { blankData } from '@/views/organization/departments/formSchemas';
  import { cloneDeep, uniq } from 'lodash-es';
  import NDropDown from '@/components/business/tooltip/index.vue';
  import { orgBlankData } from '@/views/organization/orgs/orgSchmemas';
import { json } from 'stream/consumers';
import { string } from 'vue-types';

  defineOptions({
    name: 'sys_dept',
  });
  defineComponent({
    DeptDetail
    })

  interface State {
    name: string;
    dataModel:string;
    orgId: string[];
    originData: any;
    orgTree: TreeDataItem[];
    expandedKeys:string[];
    showTree:boolean;
  }

  const [DynamicTable, dynamicTableInstance] = useTable({ formProps: { autoSubmitOnEnter: true } });

  const [ModalRender, modalRef] = useModal();
  const orgInfoRef = ref<FormInstance>();

  const searchValue = ref('');

  const searchTree = (tree, keyword, includeChildren = false) => {
    const newTree: any = [];
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.title.includes(keyword)) {
        if (!state.orgId.includes(node.key) && node.children && node.children.length) {
          state.orgId.push(node.key);
        }
        newTree.push({
          ...node,
          children: includeChildren ? searchTree(node.children || [], '', true) : [],
        });
      } else if (node.children) {
        const result = searchTree(node.children, keyword, true);
        if (result.length > 0) {
          state.orgId.push(node.key);
          newTree.push({ ...node, children: result });
        }
      }
    }
    return newTree;
  };

  watch(
    () => searchValue.value,
    (newVal) => {
      state.orgTree = searchTree(state.originData, newVal, true);
    },
  );

  const deptListLoading = ref(false);

  const state = reactive<State>({
    name: '',
    dataModel:'',
    orgId: [],
    orgTree: [],
    originData: [],
    expandedKeys:[],
    showTree:true
  });

  const orgData = reactive({
    positionList: [],
    rolesList: [],
    userList: [],
    departList: [],
  });

  /**
     * @description 打开弹窗
     */
     const editDrawerBindValue = reactive({
      orgTree: [],
      deptTree:[],
      deptItem: {},
      orgItem: {},
    });
    const openModal = async (nodeId:string,record: Partial<TableListItem> = {}) => {
      console.log(record,"record111111111111")
      editDrawerBindValue.orgTree=ref(state.orgTree);
      editDrawerBindValue.deptTree=ref(state.orgTree); 
      editDrawerBindValue.deptItem=record.id?{...record}:{...blankData};
      if(nodeId!==''){
        editDrawerBindValue.deptItem.parentId=nodeId;
      }
      
      console.log(editDrawerBindValue.deptItem,"editDrawerBindValue.deptItem1111111")

      ModalRender.show({
        title: `${record.id ? '编辑' : '新增'}部门`,
        width: '60%',
        destroyOnClose: true,
        bodyStyle:{ height: '60vh', overflowY: 'auto' },
        content: () => {
          return <DeptDetail ref={modalRef} defaultData={unref(editDrawerBindValue)}></DeptDetail>;
        },
        // 确定方法执行
        onOk: async () => {
          const [orgInfo,orgRef] = await modalRef.value?.handleSubmit();
          let res = await orgRef.value.validate()
          res.id=record.id ? record.id:"";
          if (res) {
            const result=await (record.id? updateDept :createDept)(res);
            if(result.error===200){
              state.showTree = false
              const msg=record.id ? "修改成功":"新增成功";
              message.success(msg);
              fetchCompanyList();
              dynamicTableInstance?.reload();
              nextTick(()=>state.showTree = true)
            }
          };
        },
      });
    };
    const openOrgModal = async (nodeId,record) => {
      editDrawerBindValue.orgTree=ref(state.orgTree);
      editDrawerBindValue.orgItem=record.id?{...record}:{...blankData};
      if(nodeId!==''){
        editDrawerBindValue.orgItem.parentId=nodeId;
      }
 
      ModalRender.show({
        title: `${record.id ? '编辑' : '新增'}机构`,
        width: '60%',
        destroyOnClose: true,
        bodyStyle:{ maxHeight: '60vh', overflowY: 'auto' },
        content: () => {
          return <OrgDetail ref={orgInfoRef} defaultData={unref(editDrawerBindValue)}></OrgDetail>;
        },
        // 确定方法执行
        onOk: async () => {
          const [orgInfo,orgRef] = await orgInfoRef.value?.handleSubmit();
          let res = await orgRef.value.validate()
          res.id=record.id ? record.id:"";
          console.log(res);
          if (res) {
            // const createOrgData=copyMatchingKeys(orgInfo, orgBlankData);
            // if(createOrgData.parentId!==undefined&&createOrgData.parentId.length>0&&Array.isArray(createOrgData.parentId)){
            //   const orgStr=createOrgData.parentId.map(item=>item.toString());
            //   const parentId=orgStr.join(',');
            //   createOrgData.parentId=parentId;
            // }
            // createOrgData.id=record.id ? record.id:"";
            
            const result=await (record.id? updateDept :createDept)(res);
            if(result.error===200){
              state.showTree = false
              const msg=record.id ? "修改成功":"新增成功";
              message.success(msg);
              fetchCompanyList();
              dynamicTableInstance?.reload();
              nextTick(()=>state.showTree = true)
            }
          };
        },
      });
    };
    //赋值数据
    function copyMatchingKeys<T, U>(source: T, target: U): U {
      Object.keys(source).forEach(key => {
        if (key in target) {
            (target as any)[key] = source[key];
        }
      });
      return target;
    }

  /**
   * 获取组织列表
   */
  const fetchCompanyList = async () => {
    deptListLoading.value = true;
    const res = await getDepartmentEntityList().finally(() => (deptListLoading.value = false));
    if (res && res.result) {
        const dept = flatTree(res.result);
        state.orgTree = formatDept2Tree(dept, '0');
        state.originData = state.orgTree.map((item) => item);
        state.orgId = [
        ...state.orgId,
        ...state.orgTree.map((n: any) => Number(n.id)),

        console.log(state.orgTree,"state.orgTree11111111111111111")
      ];
    }
  };

  /**
   * @description 表格删除行
   */
  const delRowConfirm = async (deptId: number) => {
    const res = await deleteDept({ id: deptId }).finally(dynamicTableInstance?.reload);
    if (res?.error == 200) {
      state.showTree = false;
      message.success('删除成功');
      fetchCompanyList();
      dynamicTableInstance?.reload();
      nextTick(()=>state.showTree = true)
    }
  };

  /**
   * 点击组织
   */
  const onTreeSelect = (selectedKeys: number[],e) => {
    console.log(selectedKeys,'selectedKeys',e);
    
    const node=e;
    if(node!=undefined){
      state.dataModel=node.dataModel;
    if(node.dataModel=="1"){
      dropItems.value =[
        {
          label: '新建部门',
          key: 'dept',
          icon: h(PlusOutlined),
        },
        {
          label: '编辑部门',
          key: 'deptInfo',
          icon: h(EditOutlined),
        },
        {
          label: '删除部门',
          key: 'deleteDept',
          icon: h(DeleteOutlined),
        },
      ];
    }
    else{
      dropItems.value = [
        {
          label: '新建机构',
          key: 'org',
          icon: h(PlusCircleOutlined),
        },
        {
          label: '新建部门',
          key: 'dept',
          icon: h(PlusOutlined),
        },
        {
          label: '编辑机构',
          key: 'orgInfo',
          icon: h(EditOutlined),
        },
        {
          label: '删除机构',
          key: 'deleteOrg',
          icon: h(DeleteOutlined),
        },
      ];
    }
    }
    else{
      dropItems.value=[];
    }
    state.orgId = selectedKeys;
    
    dynamicTableInstance?.reload?.();
  };
  const loadTableData = async (params: LoadDataParams) => {
    let  parentId="";
    if(params.name==undefined||params.name==''){
      parentId=state.orgId.length ? state.orgId[0] : '';
    }

    const data = await getDeptsList({
      ...params,
      pageSize: params.limit,
      parentId: parentId,
    });
    const deptTree = flatTree(data.rows);
    orgData.departList=deptTree;
    return {
      list: data?.rows || [],
      pagination: {
        total: data?.total,
        size: params.limit,
        page: params.pageNum,
      },
    } as API.TableListResult;
  };
  const deleteOrgInfo= async()=>{
    Modal.confirm({
    title: '确认删除',
    content: '确定要删除此机构吗？',
    okText: '确定',
    cancelText: '取消',
    centered: true, 
    async onOk() {
      const res = await deleteDept({ id: state.orgId[0] }).finally(dynamicTableInstance?.reload);
      if (res?.error == 200) {
        state.showTree = false;
        message.success('删除成功');
        fetchCompanyList();
        dynamicTableInstance?.reload();
        nextTick(()=>state.showTree = true)
      }
    }
  });
  }
  const deleteDeptInfo= async()=>{
    Modal.confirm({
    title: '确认删除',
    content: '确定要删除此部门吗？',
    okText: '确定',
    cancelText: '取消',
    centered: true, 
    async onOk() {
      const res = await deleteDept({ id: state.orgId[0] }).finally(dynamicTableInstance?.reload);
      if (res?.error == 200) {
        state.showTree = false;
        message.success('删除成功');
        fetchCompanyList();
        dynamicTableInstance?.reload();
        nextTick(()=>state.showTree = true)
      }
    }
  });
  }
  const columns: TableColumnItem[] = [
    ...baseColumns,
    {
      title: '操作',
      width: 220,
      dataIndex: 'ACTION',
      align: 'center',
      actions: ({ record }) => [
        {
          label: '编辑',
          icon: h(EditOutlined),
          onClick: () => openModal('',record),
        },
        {
          label: '删除',
          danger: true,
          icon: h(DeleteOutlined),
          popConfirm: {
            title: '你确定要删除吗？',
            onConfirm: () => delRowConfirm(record.id),
          },
        },
      ],
    },
  ];

  const handleTreeItemClick = (node, treeNode,type) => {
    console.log(node, treeNode)
    if(node.key==="org"){ 
      openOrgModal(state.orgId[0],{});
    }
    else if(node.key==="orgInfo"){
      openOrgModal('',treeNode);
    }
    else if(node.key==="deptInfo"){
      openModal('',treeNode);
    }
    else if(node.key==="dept"){
      openModal(state.orgId[0],{});
    }
    else if(node.key==="deleteOrg"){
      deleteOrgInfo();
    }
    else if(node.key==="deleteDept"){
      deleteDeptInfo();
    }
  };
  const dropItems = ref([
    {
      label: '新建机构',
      key: 'org',
      icon: h(PlusCircleOutlined),
    },
    {
      label: '新建部门',
      key: 'dept',
      icon: h(PlusOutlined),
    },
    {
      label: '编辑机构',
      key: 'orgInfo',
      icon: h(EditOutlined),
    },
    {
      label: '删除机构',
      key: 'deleteOrg',
      icon: h(DeleteOutlined),
    },
  ]);

  onMounted(() => {
    fetchCompanyList();
  });
</script>

<style lang="less" scoped>
  @import '@/styles/navTheme.less';
  @classBacks: dept-page-box;
  .customSetStyle(@classBacks, background-color, 'content-back-user');

  :deep(.ant-tree) {
    flex: 1;
  }
</style>
<style>
.left-content{
  border-radius: 10px;
}
</style>
